package com.example.javaweb.servlet;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author: dtYuMa
 * @date: 2021年08月18日 17:02
 * @description:
 */
@Slf4j
@WebServlet(urlPatterns = "/sse")
public class SseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/event-stream;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //for (int i = 0; i < 10; i++) {
        for (; ; ) {
            //out.write("id:" + i + "\n");
            //断开后重连时间间隔为20s
            //out.write("retry: 20000\n");

            log.info("客户端连接中...");

            //客户端断开连接，跳出循环
            if (out.checkError()) {
                log.info("客户端断开连接...");
                return;
            }

            out.write("data: 江南一点雨\n\n");
            out.flush();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
